package com.sz.app.oss.api.system;

import com.sz.biz.app.web.security.Des;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.BizException;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.dto.MenuItem;
import com.sz.common.core.system.entity.SysFile;
import com.sz.common.core.system.service.MenuService;
import com.sz.common.core.system.service.SysFileService;
import com.sz.common.core.system.dto.UserChangePasswordDto;
import com.sz.common.core.system.dto.UserConfigDto;
import com.sz.common.core.system.entity.UserConfig;
import com.sz.common.core.system.entity.UserDetail;
import com.sz.common.core.system.service.UserConfigService;
import com.sz.common.core.system.service.UserService;
import com.sz.app.oss.api.system.dto.UserSimpleDto;
import com.sz.app.oss.web.security.SecurityKeys;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;

/**
 * Function: 已登录用户获取当前登录用户的资源，统一在此处 <br>
 * Author: wentao.chang <br>
 * Date: 2016-11-11 14:12:00
 */
@Controller
@RequestMapping("${api}/u")
@Api(description = " ", tags = "001、已登录用户资源，统一在此处")
public class LoginedUserController {

    @Autowired
    private SecurityKeys securityKeys;

    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private UserConfigService userConfigService;
    @Autowired
    private SysFileService sysFileService;

    @ApiOperation(value = "获取当前用户的详情", notes = "-")
    @RequestMapping(value = "/profile", method = {RequestMethod.GET})
    public
    @ResponseBody
    ResultDto getUserProfile() {
        int userId = PrincipalUtils.getAccountId();
        UserDetail ud = userService.getSimpleUserById(userId);
        UserConfigDto uc = userConfigService.findAllConfigByUserId(userId);
        UserSimpleDto dto = new UserSimpleDto();
        dto.setFullName(ud.getFullName());
        dto.setUserId(userId);
        dto.setAccountName(PrincipalUtils.getAccountName());
        dto.setUc(uc);
        SysFile sysFile = sysFileService.getFileInfo(ud.getAvatarId());
        if (sysFile != null) {
            dto.setAvatarPath(sysFile.getFileLocation());
        }
        dto.setSex(ud.getSex());
        ResultDto resultDto = new ResultDto();
        resultDto.setData(dto);
        return resultDto;
    }

    @ApiOperation(value = "保存用户设置", notes = "保存用户设置")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userConfigDto", value = "提交的用户设置信息\r\n i18n,pageSize",
                    required = true, dataType = "UserConfigDto", paramType = "body")})
    @RequestMapping(value = "/userconfig", method = {RequestMethod.POST})
    public
    @ResponseBody
    ResultDto saveUserConfig(@RequestBody UserConfigDto userConfigDto)
            throws BizException, ParseException {
        // 如果没有登录 下面的方法会爆异常出去故下面不需要异常处理
        int userId = PrincipalUtils.getAccountId();
        userConfigDto.setUserId(userId);
        userConfigService.saveUserConfig(userConfigDto);
        PrincipalUtils.getPrincipal().setPreferredLanguage(userConfigDto.getI18n());
        return new ResultDto();
    }

    @ApiOperation(value = "按参数名查询用户设置的个性化参数值", notes = "按参数名查询用户设置的个性化参数值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paramname", value = "要查询的参数名",
                    required = true, dataType = "string", paramType = "path")})
    @RequestMapping(value = "/userconfig/{paramname}", method = {RequestMethod.GET})
    public
    @ResponseBody
    ResultDto findByUserIdAndParamName(@PathVariable("paramname") String paramName)
            throws BizException, ParseException {
        int userId = PrincipalUtils.getAccountId();
        UserConfig userConfig = new UserConfig();
        userConfig.setUserId(userId);
        userConfig.setParamName(paramName);
        UserConfig uc = userConfigService.findByUserIdAndParamName(userConfig);
        ResultDto dto = new ResultDto();
        dto.setData(uc);
        return dto;
    }

    @ApiOperation(value = "修改密码", notes = "修改密码")
    @ApiImplicitParams({@ApiImplicitParam(name = "userChangePasswordDto", value = "提交的用户修改密码的信息\r\n "
            + "oldPassword,newPassword", required = true, dataType = "UserChangePasswordDto", paramType = "body")})
    @RequestMapping(value = "/changepassword", method = {RequestMethod.POST})
    public
    @ResponseBody
    ResultDto changePw(@RequestBody UserChangePasswordDto userChangePasswordDto)
            throws BizException, ParseException {
        // 如果没有登录 下面的方法会爆异常出去故下面不需要异常处理
        int userId = PrincipalUtils.getAccountId();
        if (userChangePasswordDto != null) {
            userChangePasswordDto.setOldPassword(decPassword(userChangePasswordDto.getOldPassword()));
            userChangePasswordDto.setNewPassword(decPassword(userChangePasswordDto.getNewPassword()));
        }
        userService.changePassword(userId,userChangePasswordDto);
        return new ResultDto();
    }

    /**
     * 获取当前登录用户所在域的全部菜单.
     *
     * @throws Exception 异常信息
     */
    @RequestMapping(value = "/usertree", method = {RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取当前用户的菜单树", notes = "获取某个域下的当前登录用户所所拥有的菜单")
    public ResultDto getCurrUserMenu() throws Exception {

        MenuItem menuItem = menuService.getCurrUserMenu();

        ResultDto result = new ResultDto();
        result.setData(menuItem);
        return result;
    }

    private String decPassword(String password){
        String key1 = "DAB019642892EC3231802E13447D3F52";
        String key2 = "14833CB10FAF594B0874F3494AB0946E";
        String key3 = "42099DDB28D27ADFCFD3E961BE6E08D5";
        if (StringUtils.isNotBlank(password)) {
            return Des.getDesTool().strDec(password, securityKeys.getSecurityKey1(), securityKeys.getSecurityKey2(), securityKeys.getSecurityKey3());
        }
        return password;
    }
}
